/**
 * JS工具
 *
 * @param value
 * @returns {string}
 */
init();

function init() {
    cls_blank_input_text();
}

function cls_blank_input_text() {
    $(":input:text").bind("blur", function () {
        $(this).val(do_trim($(this).val()));
    });
}

function cls_blank_textarea(id) {
    $("#" + id).bind("blur", function () {
        $(this).val(do_trim($(this).val()));
    });
}

function get_apply_status_lab(status) {
    switch (status) {
        case ApplyStatus.ABANONED:
            return ApplyStatusLab.ABANONED;
        case ApplyStatus.DRAFT:
            return ApplyStatusLab.DRAFT;
        case ApplyStatus.PRE_AUDIT:
            return ApplyStatusLab.PRE_AUDIT;
        case ApplyStatus.RETURN_APPLY:
            return ApplyStatusLab.RETURN_APPLY;
        case ApplyStatus.CONFIRM_RELEASE:
            return ApplyStatusLab.CONFIRM_RELEASE;
        case ApplyStatus.PRE_RELEASE:
            return ApplyStatusLab.PRE_RELEASE;
        case ApplyStatus.FILL_CONFIG:
            return ApplyStatusLab.FILL_CONFIG;
        case ApplyStatus.PRE_SIGN:
            return ApplyStatusLab.PRE_SIGN;
        case ApplyStatus.PRE_ONLINE:
            return ApplyStatusLab.PRE_ONLINE;
        case ApplyStatus.PRE_REVERT:
            return ApplyStatusLab.PRE_REVERT;
        case ApplyStatus.ONLINE:
            return ApplyStatusLab.ONLINE;
        case ApplyStatus.REVERT:
            return ApplyStatusLab.REVERT;
        case ApplyStatus.REVERT_ING:
            return ApplyStatusLab.REVERT_ING;
        case ApplyStatus.RELEASE_ING:
            return ApplyStatusLab.RELEASE_ING;
    }
    return "未知";
}

function is_support_reject_btn(status) {
    switch (status) {
        case ApplyStatus.PRE_AUDIT:
            return true;
        case ApplyStatus.FILL_CONFIG:
            return true;
        case ApplyStatus.PRE_SIGN:
            return true;
        default:
            return false;
    }
}

function get_next_status_btn(status, pass, fill) {
    switch (status) {
        case ApplyStatus.PRE_AUDIT:
            if (pass) {
                return fill ? "确认补填" : "确认审核";
            }
            return "退回申请";
        case ApplyStatus.FILL_CONFIG:
            return pass ? "完成补填" : "退回申请";
        case ApplyStatus.CONFIRM_RELEASE:
            return "确认发布";
        case ApplyStatus.PRE_RELEASE:
            return "执行发布";
        case ApplyStatus.PRE_SIGN:
            return pass ? "确认签字" : "申请回滚";
        case ApplyStatus.PRE_ONLINE:
            return "执行上线";
        case ApplyStatus.PRE_REVERT:
            return "执行回滚";
        case ApplyStatus.REVERT_ING:
            return "再次回滚";
        case ApplyStatus.RELEASE_ING:
            return "再次发布";
        default:
            return "NA";
    }
}

function init_all_area_id_sbox(sbox_id) {
    let params = {};
    init_kv_sbox(ApiConfig.AREA_LIST, params, sbox_id, true, false);
}

function init_app_id_mult_sbox(area_id_sbox, app_id_sbox) {
    var params = {};
    params.areaId = $("#" + area_id_sbox).val();
    $.ajax({
        url: ApiConfig.APP_BY_AREAID,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        $("#" + app_id_sbox + " option").remove();
        $("#" + app_id_sbox).append(`<option value="">请选择</option>`);
        if (resp.status == 0) {
            var apps = resp.content.rows;
            for (var i = 0; i < apps.length; i++) {
                $("#" + app_id_sbox).append(`<option value="${apps[i].appId}">${apps[i].appId}-${apps[i].appName}</option>`);
            }
            $("#" + app_id_sbox).selectpicker('refresh');
        }
        //click dashboard reject_apply_btn init data
        let select_app = sessionStorage.getItem(ApiConfig.SESSION_DASHBOARD_SELECT_APP);
        sessionStorage.removeItem(ApiConfig.SESSION_DASHBOARD_SELECT_APP);
        if (select_app && select_app != "") {
            let app_info = select_app.split("_");
            $("#search_appId").selectpicker("val", app_info[1]);
            $("#search_appId").val(app_info[1]);
            $("#search_appId").find("option[value='" + app_info[1] + "']").attr("selected", true);
            //
            $("#search_status").selectpicker("val", app_info[2]);
            $("#search_status").val(app_info[2]);
            $("#search_status").find("option[value='" + app_info[2] + "']").attr("selected", true);
            //
            $("#search_btn").click();
        }
    }).fail(function () {
    });
}

function init_app_id_sbox(sbox_id, row, ignore_picker) {
    let params = {};
    params.areaId = get_area_id_from_session();
    $.ajax({
        url: ApiConfig.APP_BY_AREAID,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        $("#" + sbox_id + " option").remove();
        $("#" + sbox_id).append(`<option value="">请选择</option>`);
        if (resp.status == 0) {
            var apps = resp.content.rows;
            for (var i = 0; i < apps.length; i++) {
                // s1:
                $("#" + sbox_id).append(`<option value="${apps[i].appId}">${apps[i].appId}-${apps[i].appName}</option>`);
            }
            // s2:
            if (row != null) {
                $("#" + sbox_id + " option[value='" + row.appId + "']").attr("selected", true);
            }
            if (!ignore_picker) {
                $("#" + sbox_id).selectpicker('refresh');
            }
        }
    }).fail(function () {
    });
}

function init_all_area_and_app_sbox(area_id_sbox, app_id_sbox) {
    let params = {};
    $.ajax({
        url: ApiConfig.AREA_LIST,
        type: "post",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(params)
    }).done(function (resp) {
        $("#" + area_id_sbox + " option").remove();
        $("#" + area_id_sbox).append(`<option value="">请选择</option>`);
        if (resp.status == 0) {
            let rowList = resp.content.rows;
            $(rowList).each(function (i, list) {
                $("#" + area_id_sbox).append(`<option value="${list.key}">${list.key}-${list.value}</option>`);
            });
            $("#" + area_id_sbox).selectpicker('refresh');
            init_app_id_mult_sbox(area_id_sbox, app_id_sbox);
        } else {
            alert_tip("提示", resp.message);
        }
    })
}

function alert_tip(title, content) {
    $.alert({title: title, content: content, buttons: {confirm: {text: "确定"}}});
}

function date_format(value) {
    if (value == null || value == undefined) {
        return "";
    }
    return value > 0 ? moment(value).format("YYYY-MM-DD HH:mm:ss") : 0;
}

function mask_text(value) {
    if (value == null || value == undefined) {
        return "";
    }
    if (value.length > 15) {
        return value.substring(0, 15) + "...";
    }
    return value;
}

function get_area_id_from_session() {
    return sessionStorage.getItem(ApiConfig.SESSION_INDEX_AREA_ID);
}

function set_row_btn_permission(rows, display) {
    //reset row btn permission
    if (rows && display) {
        for (var i = 0; i < rows.length; i++) {
            rows[i].btn_display = display;
        }
    }
    return rows;
}

function fillUUID(id) {
    $("#" + id).val(createUUID());
}

function createUUID() {
    getRandom = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (getRandom() + getRandom() + getRandom() + getRandom() + getRandom() + getRandom() + getRandom() + getRandom());
}

//追加行
function append_tr_func(tdobject) {
    var td = $(tdobject);
    if ($("#para_table tr").length >= 20) {
        return;
    }
    var tr = td.parents("tr").clone();
    prop_key_mult_sbox('appId', 'propFile', tr);
    $("#para_table").append(tr);
}

function change_prop_def_value(tdobject) {
    var td = $(tdobject);
    var value = td.val();
    var tr = td.parents("tr");
    if (value == "-1") {
        $(tr.find("input")[1]).val("NA");
    } else {
        $(tr.find("input")[1]).val("");
    }
}

//删除行
function del_tr_func(tdobject) {
    var td = $(tdobject);
    if ($("#para_table tr").length <= 2) {
        return;
    }
    td.parents("tr").remove();
}

function git_config_push_func(applyId, areaId, appId, retry) {
    var params = {};
    params.applyId = applyId || "";
    params.areaId = areaId || "";
    params.appId = appId || "";
    params.retry = retry;
    //
    let apiUrl = ApiConfig.GIT_CONFIG_PUSH;
    if (retry) {
        apiUrl += append_ua_pc(PagePathCode.C0002);
    } else {
        apiUrl += append_ua_pc(PagePathCode.C0001);
    }
    $.ajax({
        url: apiUrl,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        if (resp.status == 0) {
            alert_tip("提示", "发布成功！");
            $("#view_audit_modal").modal('hide');
            $("#search_btn").click();
        } else {
            alert_tip("提示", resp.message);
        }
    }).fail(function () {
        alert_tip("提示", "发布失败！");
    });
}

function git_config_revert_func(applyId, areaId, appId, status, retry) {
    var params = {};
    params.applyId = applyId || "";
    params.areaId = areaId || "";
    params.appId = appId || "";
    params.status = status || null;
    params.decision = AuditResult.AUDIT_REJECT;
    params.retry = retry;
    $.ajax({
        url: ApiConfig.GIT_CONFIG_REVERT,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        if (resp.status == 0) {
            alert_tip("提示", "回滚成功！");
            $("#view_audit_modal").modal('hide');
            $("#search_btn").click();
        } else {
            alert_tip("提示", resp.message);
        }
    }).fail(function () {
        alert_tip("提示", "回滚失败！");
    });
}

function get_user_opt_type_lab(status) {
    switch (status) {
        case UserOptType.LOGIN:
            return UserOptTypeLab.LOGIN;
        case UserOptType.ADD:
            return UserOptTypeLab.ADD;
        case UserOptType.AUDIT_OK:
            return UserOptTypeLab.AUDIT_OK;
        case UserOptType.AUDIT_FAIL:
            return UserOptTypeLab.AUDIT_FAIL;
        case UserOptType.RELEASE_SUCCESS:
            return UserOptTypeLab.RELEASE_SUCCESS;
        case UserOptType.RELEASE_FAIL:
            return UserOptTypeLab.RELEASE_FAIL;
        case UserOptType.DELETE:
            return UserOptTypeLab.DELETE;
        case UserOptType.ABANDONED:
            return UserOptTypeLab.ABANDONED;
        case UserOptType.REVERT_FAIL:
            return UserOptTypeLab.REVERT_FAIL;
        case UserOptType.REVERT_SUCCESS:
            return UserOptTypeLab.REVERT_SUCCESS;
        case UserOptType.MODIFY:
            return UserOptTypeLab.MODIFY;
        case UserOptType.FILL_CONFIG:
            return UserOptTypeLab.FILL_CONFIG;
        case UserOptType.SIGN:
            return UserOptTypeLab.SIGN;
        case UserOptType.SYNC_REMOTE_GIT_CFG:
            return UserOptTypeLab.SYNC_REMOTE_GIT_CFG;
        case UserOptType.DEL_REMOTE_GIT_CFG:
            return UserOptTypeLab.DEL_REMOTE_GIT_CFG;
        case UserOptType.SYNC_REMOTE_BIZ_KEY:
            return UserOptTypeLab.SYNC_REMOTE_BIZ_KEY;
        case UserOptType.RELEASE_ING:
            return UserOptTypeLab.RELEASE_ING;
        case UserOptType.REVERT_ING:
            return UserOptTypeLab.REVERT_ING;
        case UserOptType.LOGOUT:
            return UserOptTypeLab.LOGOUT;
        case UserOptType.FAST_PUB_CFG:
            return UserOptTypeLab.FAST_PUB_CFG;
        case UserOptType.SPEC_PUB_CFG:
            return UserOptTypeLab.SPEC_PUB_CFG;
        case UserOptType.OPEN_DEC_ERR_LIMIT:
            return UserOptTypeLab.OPEN_DEC_ERR_LIMIT;
        case UserOptType.CLOSE_DEC_ERR_LIMIT:
            return UserOptTypeLab.CLOSE_DEC_ERR_LIMIT;
        case UserOptType.BULK_PUBLISH_CFG:
            return UserOptTypeLab.BULK_PUBLISH_CFG;
        case UserOptType.BULK_DOWNLOAD_CFG:
            return UserOptTypeLab.BULK_DOWNLOAD_CFG;
        case UserOptType.SCHEDULE_TASK:
            return UserOptTypeLab.SCHEDULE_TASK;
    }
    return "未知";
}

function fmt_ymd_hms(id) {
    $("#" + id).datetimepicker({
        format: 'Y-m-d H:i:s',
        step: 1
    });
}

function apply_audit_reject_func() {
    var params = {};
    params.applyId = $("#applyId").val() || "";
    params.status = $("#hide_status").val() || null;
    params.decision = AuditResult.AUDIT_REJECT;
    $.ajax({
        url: ApiConfig.APPLY_STATUS_UPDATE,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        if (resp.status == 0) {
            alert_tip("提示", "操作成功！");
            $("#view_audit_modal").modal('hide');
            $("#search_btn").click();
        } else {
            alert_tip("提示", resp.message);
        }
    }).fail(function () {
        alert_tip("提示", "操作失败！");
    });
}

function apply_audit_pass_func() {
    var params = {};
    params.applyId = $("#applyId").val() || "";
    params.status = $("#hide_status").val() || null;
    params.decision = AuditResult.AUDIT_PASS;
    params.detailList = new Array();
    if (params.status == ApplyStatus.FILL_CONFIG) {
        let rows = $("#para_table tbody tr");
        let needFill = false;
        for (var i = 0; i < rows.length; i++) {
            let inputs = $(rows[i]).find("input");
            let selects = $(rows[i]).find("select");
            //
            let id = inputs[0].value || null;
            let propKey = inputs[1].value || "";
            let propValue = inputs[2].value || "";
            let defaultValue = selects[0].value || "";
            var showMask = true;
            var hashValue = true;
            //
            if (defaultValue == "-1") {
                needFill = true;
            }
            var detail = {};
            detail.id = id;
            detail.applyId = params.applyId;
            detail.propKey = propKey;
            detail.propValue = propValue;
            detail.defaultValue = defaultValue;
            detail.showMask = showMask;
            detail.hashValue = hashValue;
            params.detailList[i] = detail;
        }
        if (needFill) {
            alert_tip("提示", "请补填完配置后再提交");
            return;
        }
    }
    $.ajax({
        url: ApiConfig.APPLY_STATUS_UPDATE,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        if (resp.status == 0) {
            alert_tip("提示", "操作成功！");
            $("#view_audit_modal").modal('hide');
            $("#search_btn").click();
        } else {
            alert_tip("提示", resp.message);
        }
    }).fail(function () {
        alert_tip("提示", "操作失败！");
    });
}

function init_release_status_sbox(sbox_id, ignore_picker) {
    //6-已发布待签字 7-待上线 8-待回滚 9-已上线 10-已回滚 98-回滚中 99-发布中
    let html = '<option value="">请选择</option>' +
        '<option value="' + ApplyStatus.PRE_SIGN + '">' + ApplyStatusLab.PRE_SIGN + '</option>' +
        '<option value="' + ApplyStatus.PRE_ONLINE + '">' + ApplyStatusLab.PRE_ONLINE + '</option>' +
        '<option value="' + ApplyStatus.PRE_REVERT + '">' + ApplyStatusLab.PRE_REVERT + '</option>' +
        '<option value="' + ApplyStatus.ONLINE + '">' + ApplyStatusLab.ONLINE + '</option>' +
        '<option value="' + ApplyStatus.REVERT + '">' + ApplyStatusLab.REVERT + '</option>' +
        '<option value="' + ApplyStatus.REVERT_ING + '">' + ApplyStatusLab.REVERT_ING + '</option>' +
        '<option value="' + ApplyStatus.RELEASE_ING + '">' + ApplyStatusLab.RELEASE_ING + '</option>';
    $("#" + sbox_id).append(html);
    if (!ignore_picker) {
        $("#" + sbox_id).selectpicker('refresh');
    }
}

// -1-已废弃 0-草稿 1-待审核 2-退回申请 3-待确认发布 4-待发布 5-补填配置 7-待上线 8-待回滚 98-回滚中 99-发布中
function init_apply_status_sbox(sbox_id, ignore_picker) {
    let html = '<option value="">请选择</option>' +
        '<option value="' + ApplyStatus.ABANONED + '">' + ApplyStatusLab.ABANONED + '</option>' +
        '<option value="' + ApplyStatus.DRAFT + '">' + ApplyStatusLab.DRAFT + '</option>' +
        '<option value="' + ApplyStatus.PRE_AUDIT + '">' + ApplyStatusLab.PRE_AUDIT + '</option>' +
        '<option value="' + ApplyStatus.RETURN_APPLY + '">' + ApplyStatusLab.RETURN_APPLY + '</option>' +
        '<option value="' + ApplyStatus.CONFIRM_RELEASE + '">' + ApplyStatusLab.CONFIRM_RELEASE + '</option>' +
        '<option value="' + ApplyStatus.PRE_RELEASE + '">' + ApplyStatusLab.PRE_RELEASE + '</option>' +
        '<option value="' + ApplyStatus.FILL_CONFIG + '">' + ApplyStatusLab.FILL_CONFIG + '</option>' +
        '<option value="' + ApplyStatus.PRE_ONLINE + '">' + ApplyStatusLab.PRE_ONLINE + '</option>' +
        '<option value="' + ApplyStatus.PRE_REVERT + '">' + ApplyStatusLab.PRE_REVERT + '</option>' +
        '<option value="' + ApplyStatus.REVERT_ING + '">' + ApplyStatusLab.REVERT_ING + '</option>' +
        '<option value="' + ApplyStatus.RELEASE_ING + '">' + ApplyStatusLab.RELEASE_ING + '</option>';
    $("#" + sbox_id).append(html);
    if (!ignore_picker) {
        $("#" + sbox_id).selectpicker('refresh');
    }
}

function init_user_opt_type_sbox(sbox_id, ignore_picker) {
    let html = '<option value="">请选择</option>' +
        '<option value="' + UserOptType.LOGIN + '">' + UserOptTypeLab.LOGIN + '</option>' +
        '<option value="' + UserOptType.ADD + '">' + UserOptTypeLab.ADD + '</option>' +
        '<option value="' + UserOptType.AUDIT_OK + '">' + UserOptTypeLab.AUDIT_OK + '</option>' +
        '<option value="' + UserOptType.AUDIT_FAIL + '">' + UserOptTypeLab.AUDIT_FAIL + '</option>' +
        '<option value="' + UserOptType.RELEASE_SUCCESS + '">' + UserOptTypeLab.RELEASE_SUCCESS + '</option>' +
        '<option value="' + UserOptType.RELEASE_FAIL + '">' + UserOptTypeLab.RELEASE_FAIL + '</option>' +
        '<option value="' + UserOptType.DELETE + '">' + UserOptTypeLab.DELETE + '</option>' +
        '<option value="' + UserOptType.ABANDONED + '">' + UserOptTypeLab.ABANDONED + '</option>' +
        '<option value="' + UserOptType.REVERT_FAIL + '">' + UserOptTypeLab.REVERT_FAIL + '</option>' +
        '<option value="' + UserOptType.REVERT_SUCCESS + '">' + UserOptTypeLab.REVERT_SUCCESS + '</option>' +
        '<option value="' + UserOptType.MODIFY + '">' + UserOptTypeLab.MODIFY + '</option>' +
        '<option value="' + UserOptType.FILL_CONFIG + '">' + UserOptTypeLab.FILL_CONFIG + '</option>' +
        '<option value="' + UserOptType.SIGN + '">' + UserOptTypeLab.SIGN + '</option>' +
        '<option value="' + UserOptType.SYNC_REMOTE_GIT_CFG + '">' + UserOptTypeLab.SYNC_REMOTE_GIT_CFG + '</option>' +
        '<option value="' + UserOptType.DEL_REMOTE_GIT_CFG + '">' + UserOptTypeLab.DEL_REMOTE_GIT_CFG + '</option>' +
        '<option value="' + UserOptType.SYNC_REMOTE_BIZ_KEY + '">' + UserOptTypeLab.SYNC_REMOTE_BIZ_KEY + '</option>' +
        '<option value="' + UserOptType.RELEASE_ING + '">' + UserOptTypeLab.RELEASE_ING + '</option>' +
        '<option value="' + UserOptType.REVERT_ING + '">' + UserOptTypeLab.REVERT_ING + '</option>' +
        '<option value="' + UserOptType.LOGOUT + '">' + UserOptTypeLab.LOGOUT + '</option>' +
        '<option value="' + UserOptType.FAST_PUB_CFG + '">' + UserOptTypeLab.FAST_PUB_CFG + '</option>' +
        '<option value="' + UserOptType.SPEC_PUB_CFG + '">' + UserOptTypeLab.SPEC_PUB_CFG + '</option>' +
        '<option value="' + UserOptType.OPEN_DEC_ERR_LIMIT + '">' + UserOptTypeLab.OPEN_DEC_ERR_LIMIT + '</option>' +
        '<option value="' + UserOptType.CLOSE_DEC_ERR_LIMIT + '">' + UserOptTypeLab.CLOSE_DEC_ERR_LIMIT + '</option>' +
        '<option value="' + UserOptType.BULK_PUBLISH_CFG + '">' + UserOptTypeLab.BULK_PUBLISH_CFG + '</option>' +
        '<option value="' + UserOptType.BULK_DOWNLOAD_CFG + '">' + UserOptTypeLab.BULK_DOWNLOAD_CFG + '</option>' +
        '<option value="' + UserOptType.SCHEDULE_TASK + '">' + UserOptTypeLab.SCHEDULE_TASK + '</option>';
    $("#" + sbox_id).append(html);
    if (!ignore_picker) {
        $("#" + sbox_id).selectpicker('refresh');
    }
}

function init_yes_no_sbox(sbox_id) {
    $("#" + sbox_id).append('<option value="false" selected>否</option><option value="true">是</option>');
}

function init_default_value_sbox(sbox_id) {
    $("#" + sbox_id).append('<option value="0" selected>0</option><option value="*">*</option><option value="-1">补填</option>');
}

function init_redis_type_sbox(sbox_id) {
    $("#" + sbox_id).append('<option value="" selected>请选择</option><option value="0">普通Key</option><option value="1">ZCache</option>');
}

function get_draw_red_html(content) {
    if (content == null || content == undefined) {
        return "<br/><br/><br/><br/><br/>";
    }
    let html = "";
    let cc = content.split("\n");
    for (let i = 0; i < cc.length; i++) {
        if (cc[i].startsWith("-")) {
            html += "<b style='color: red;'>" + cc[i] + "</b>";
        } else if (cc[i].startsWith("+")) {
            html += "<b style='color: green;'>" + cc[i] + "</b>";
        } else {
            html += cc[i];
        }
        html += "<br/>";
    }
    html += "<br/>";
    return html;
}

function detail_select_prop_file(app_id_sbox, prop_file_id, row) {
    let params = {};
    params.areaId = get_area_id_from_session();
    params.appId = $("#" + app_id_sbox).val() || null;
    if (params.appId == null && row != null) {
        params.appId = row.appId;
    }
    if (params.appId == null) {
        return;
    }
    $.ajax({
        url: ApiConfig.REMOTE_CFG_FILE_GET,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        $("#propFile").empty();
        if (resp.status == 0
            && resp.content != null
            && resp.content.length > 0) {
            //
            let html = '<option value="">请选择</option>';
            $(resp.content).each(function (i, item) {
                html += '<option value="' + item + '">' + item + '</option>';
            });
            // s1:
            $("#propFile").append(html);
            // s2:
            if (row != null) {
                $("#propFile option[value='" + row.propFile + "']").attr("selected", true);
            }
            reset_detail_prop_file_mult_sbox();
            detail_prop_file_mult_sbox(app_id_sbox, prop_file_id, row);
        }
    }).fail(function () {
    });
}

function reset_detail_prop_file_mult_sbox() {
    var trs = $("#add_apply_modal tbody tr");
    for (let i = 1; i < trs.length; i++) {
        $(trs[i]).remove();
    }
}

function detail_prop_file_mult_sbox(app_id_sbox, prop_file_id, row) {
    let info = {
        applyId: row.applyId
    };
    $.ajax({
        url: ApiConfig.APPLY_DETAIL,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(info)
    }).done(function (resp) {
        if (resp.status == 0) {
            var subRows = resp.content.rows;
            for (var r = 0; r < subRows.length; r++) {
                var tr = $($("#add_apply_modal tbody tr")[0]);
                var currTr = tr;
                if (r > 0) {
                    currTr = tr.clone();
                    $("#add_apply_modal tbody").append(currTr);
                }
                // select prop key
                prop_key_mult_sbox('appId', 'propFile', currTr, subRows[r]);
            }
        } else {
            alert_tip("提示", resp.message);
        }
    });
}

function prop_file_mult_sbox(app_id_sbox, row) {
    init_prop_file_sbox(app_id_sbox, row);
    $("#" + app_id_sbox).change(function () {
        $("#propFile").empty();
        //
        init_prop_file_sbox(app_id_sbox, row);
    });
}

function init_prop_file_sbox(app_id_sbox, row) {
    let params = {};
    params.areaId = get_area_id_from_session();
    params.appId = $("#" + app_id_sbox).val() || null;
    if (params.appId == null && row != null) {
        params.appId = row.appId;
    }
    if (params.appId == null) {
        return;
    }
    $.ajax({
        url: ApiConfig.REMOTE_CFG_FILE_GET,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        $("#propFile").empty();
        if (resp.status == 0
            && resp.content != null
            && resp.content.length > 0) {
            //
            let html = '<option value="">请选择</option>';
            $(resp.content).each(function (i, item) {
                html += '<option value="' + item + '">' + item + '</option>';
            });
            // s1:
            $("#propFile").append(html);
            $("#propFile").selectpicker('refresh');
            // s2:
            if (row != null) {
                $("#propFile option[value='" + row.propFile + "']").attr("selected", true);
                $("#propFile").selectpicker("val", row.propFile);
            }
        }
    }).fail(function () {
    });
}

function prop_key_mult_sbox(app_id_sbox, prop_file_id, row, row_data) {
    init_prop_key_sbox(app_id_sbox, prop_file_id, row, row_data);
    $("#" + prop_file_id).change(function () {
        init_prop_key_sbox(app_id_sbox, prop_file_id, row);
    });
}

function init_prop_key_sbox(app_id_sbox, prop_file_id, row, row_data) {
    let selects = $(row).find("select");
    $(selects[0]).empty();
    //
    let params = {};
    params.areaId = get_area_id_from_session();
    params.appId = $("#" + app_id_sbox).val() || null;
    params.filename = $("#" + prop_file_id).val() || null;
    if (params.appId == null) {
        $(selects[0]).val("请选择'应用编号'！");
        return;
    }
    if (params.filename == null) {
        $(selects[0]).val("请选择'所属文件'！");
        return;
    }
    $.ajax({
        url: ApiConfig.REMOTE_CFG_KEY_GET,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(params)
    }).done(function (resp) {
        $(selects[0]).empty();
        if (resp.status == 0
            && resp.content != null
            && resp.content.length > 0) {
            //
            let html = '';
            $(resp.content).each(function (i, item) {
                html += '<option value="' + item + '">' + item + '</option>';
            });
            $(selects[0]).append(html);
            if (row_data) {
                $(row.find("input")[0]).val(row_data.propValue);
                $(row.find("select")[0]).val(row_data.propKey);
                $(row.find("select")[1]).val(row_data.defaultValue);
            }
        }
    }).fail(function () {
    });
}

function auto_select_prop_file(app_id_sbox) {
    let obj = $("#propFile");
    obj.typeahead({
        delay: 200,
        source: function (query, process) {
            var params = {};
            params.areaId = get_area_id_from_session();
            params.appId = $("#" + app_id_sbox).val() || null;
            params.prefix = do_trim(query) || null;
            if (params.appId == null) {
                obj.val("请选择'应用编号'！");
                return;
            }
            if (params.prefix == null) {
                return;
            }
            $.ajax({
                url: ApiConfig.REMOTE_CFG_FILE_GET,
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(params)
            }).done(function (resp) {
                if (resp.status == 0
                    && resp.content != null
                    && resp.content.length > 0) {
                    let content = resp.content;
                    //
                    var results = [];
                    for (let i = 0; i < content.length; i++) {
                        results.push(content[i]);
                    }
                    process(content);
                }
            }).fail(function () {
            });
        },
        afterSelect: function (item) {
            $("#propFile").val(item);
        }
    });
}

function auto_select_prop_key(app_id_sbox, prop_file_id, row) {
    var inputs = $(row).find("input");
    $(inputs[0]).typeahead({
        delay: 200,
        source: function (query, process) {
            var params = {};
            params.areaId = get_area_id_from_session();
            params.appId = $("#" + app_id_sbox).val() || null;
            params.filename = $("#" + prop_file_id).val() || null;
            params.prefix = do_trim(query) || null;
            if (params.appId == null) {
                $(inputs[0]).val("请选择'应用编号'！");
                return;
            }
            if (params.filename == null) {
                $(inputs[0]).val("请选择'所属文件'！");
                return;
            }
            if (params.prefix == null) {
                return;
            }
            $.ajax({
                url: ApiConfig.REMOTE_CFG_KEY_GET,
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(params)
            }).done(function (resp) {
                if (resp.status == 0
                    && resp.content != null
                    && resp.content.length > 0) {
                    let content = resp.content;
                    //
                    var results = [];
                    for (let i = 0; i < content.length; i++) {
                        results.push(content[i]);
                    }
                    process(content);
                }
            }).fail(function () {
            });
        },
        afterSelect: function (item) {
            $(inputs[0]).val(item);
        }
    });
}

function get_bizkey_status_lab(status) {
    switch (status) {
        case BizKeyStatus.ADD_NU:
            return BizKeyStatusLab.ADD_NU;
        case BizKeyStatus.OFFLINE_UD:
            return BizKeyStatusLab.OFFLINE_UD;
        case BizKeyStatus.ONLINE_UD:
            return BizKeyStatusLab.ONLINE_UD;
    }
    return "未知";
}

function get_task_status_lab(status) {
    switch (status) {
        case TaskStatus.OPENED:
            return TaskStatusLab.OPENED;
        case TaskStatus.CLOSED:
            return TaskStatusLab.CLOSED;
    }
    return "未知";
}

function do_trim(value) {
    if (value == undefined) {
        return;
    }
    return value.replace(/(^\s*)|(\s*$)/g, "");
}

function init_kv_sbox(url, params, sbox_id, is_append_blank_opt, ignore_picker) {
    $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(params)
    }).done(function (resp) {
        if (resp.status == 0 && resp.content != null) {
            $("#" + sbox_id + " option").remove();
            if (is_append_blank_opt) {
                $("#" + sbox_id).append('<option value="">请选择</option>');
            }
            let rowList = resp.content.rows;
            $(rowList).each(function (i, list) {
                $("#" + sbox_id).append(`<option value="${list.key}">${list.key}-${list.value}</option>`);
            });
            if (!ignore_picker) {
                $("#" + sbox_id).selectpicker('refresh');
            }
        } else {
            alert_tip("提示", resp.message);
        }
    })
}

function init_biztype_sbox(sbox_id) {
    let params = {};
    init_kv_sbox(ApiConfig.BIZ_TYPE_LIST, params, sbox_id, true, false);
}

function task_list_search_sbox(appid_sbox_id, hostname_sbox_id, ignore_picker) {
    // app_id
    init_app_id_sbox(appid_sbox_id, null, ignore_picker);
    $("#" + appid_sbox_id).change(function () {
        let params = {};
        params.areaId = get_area_id_from_session();
        params.appId = $("#" + appid_sbox_id).val() || null;
        // hostname
        init_kv_sbox(ApiConfig.HOST_NAME_LIST, params, hostname_sbox_id, true, ignore_picker);
    });
}

function task_schedule_sbox(appid_sbox_id, hostname_sbox_id, propkey_sbox_id) {
    // app_id
    init_app_id_sbox(appid_sbox_id, null, false);
    $("#" + appid_sbox_id).change(function () {
        let params = {};
        params.areaId = get_area_id_from_session();
        params.appId = $("#" + appid_sbox_id).val() || null;
        // hostname
        init_kv_sbox(ApiConfig.HOST_NAME_LIST, params, hostname_sbox_id, false, true);
        // prop key
        init_kv_sbox(ApiConfig.TASK_PROP_KEY_LIST, params, propkey_sbox_id, false, true);
    });
}

function is_invalid_form(form_id) {
    let $form = $("#" + form_id);
    $form.data("bootstrapValidator").resetForm();
    $form.data("bootstrapValidator").validate();
    return (!$form.data("bootstrapValidator").isValid());
}

function reset_form_values(form_id) {
    $("#" + form_id).data("bootstrapValidator").resetForm();
    //清空text表单数据
    $("#" + form_id + " input[type='text']").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            $("#" + id).val("");
            $("#" + id).removeAttr("readonly");
        }
    });
    //清空select表单数据
    $("#" + form_id + " select").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            $("#" + id).val("");
            $("#" + id).prop('disabled', false);
            $("#" + id).selectpicker("val", "");
        }
    });
    //清空textarea表单数据
    $("#" + form_id + " textarea").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            $("#" + id).val("");
            $("#" + id).removeAttr("readonly");
        }
    });
}

function get_form_params(form_id) {
    return get_form_params_x(form_id, null);
}

function get_form_params_x(form_id, id_prefix) {
    var params = {};
    $("#" + form_id).data("bootstrapValidator").resetForm();
    //获取text表单数据
    $("#" + form_id + " input[type='text']").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            let propName = id;
            if (id_prefix != null) {
                propName = propName.replace(id_prefix, "");
            }
            params["" + propName + ""] = $("#" + id).val() || null;
        }
    });
    //获取select表单数据
    $("#" + form_id + " select").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            let propName = id;
            if (id_prefix != null) {
                propName = propName.replace(id_prefix, "");
            }
            params["" + propName + ""] = $("#" + id).val() || null;
        }
    });
    //获取textarea表单数据
    $("#" + form_id + " textarea").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            let propName = id;
            if (id_prefix != null) {
                propName = propName.replace(id_prefix, "");
            }
            params["" + propName + ""] = $("#" + id).val() || null;
        }
    });
    return params;
}

function set_form_values(form_id, rows, is_readonly) {
    set_form_values_x(form_id, rows, is_readonly, null);
}

function set_form_values_x(form_id, rows, is_readonly, bool_id) {
    set_form_values_x2(form_id, rows, is_readonly, bool_id, null);
}

function set_form_values_x2(form_id, rows, is_readonly, bool_id, id_prefix) {
    $("#" + form_id).data("bootstrapValidator").resetForm();
    //设置text表单数据
    $("#" + form_id + " input[type='text']").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            let propName = id;
            if (id_prefix != null) {
                propName = propName.replace(id_prefix, "");
            }
            let value = rows["" + propName + ""] || null;
            $("#" + id).val(value);
            if (is_readonly) {
                $("#" + id).attr("readonly", "readonly");
            } else {
                $("#" + id).removeAttr("readonly");
            }
        }
    });
    //设置select表单数据
    $("#" + form_id + " select").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            let propName = id;
            if (id_prefix != null) {
                propName = propName.replace(id_prefix, "");
            }
            let value = rows["" + propName + ""] || null;
            // true or false
            if (bool_id != null && bool_id == id) {
                value = value ? "true" : "false";
            }
            $("#" + id).selectpicker("val", value);
            $("#" + id).prop('disabled', is_readonly);
        }
    });
    //设置textarea表单数据
    $("#" + form_id + " textarea").each(function () {
        let id = $(this).attr("id");
        if (id != null) {
            let propName = id;
            if (id_prefix != null) {
                propName = propName.replace(id_prefix, "");
            }
            let value = rows["" + propName + ""] || null;
            $("#" + id).val(value);
            if (is_readonly) {
                $("#" + id).attr("readonly", "readonly");
            } else {
                $("#" + id).removeAttr("readonly");
            }
        }
    });
}
